package com.example.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.common.to.es.SkuEsModel;
import com.example.common.utils.R;
import com.example.gulimall.search.config.GulimallElasticsearchConfig;
import com.example.gulimall.search.constant.EsConstant;
import com.example.gulimall.search.feign.ProductFeignService;
import com.example.gulimall.search.service.ElasticSearchService;
import com.example.gulimall.search.vo.AttrResponseVo;
import com.example.gulimall.search.vo.SearchParam;
import com.example.gulimall.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.nio.ch.Net;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * es业务层处理
 * @author GuLin
 * @date 2021-06-22 20:03
 */
@Slf4j
@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {

    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Autowired
    ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam param) {
        SearchResult searchResult = null;
        //通过请求参数查询构建参数
        SearchRequest request = bulidSearchRequest(param);
        try {
            SearchResponse response = restHighLevelClient.search(request, GulimallElasticsearchConfig.COMMON_OPTIONS);
            // 将es响应数据封装成结果
            searchResult = bulidSearchResult(param,response);
        } catch (IOException e) {
            log.error("es查询异常:"+e.getMessage());
            //e.printStackTrace();
        }
        return searchResult;
    }

    /**
     * 请求参数封装处理
     * @author GuLin
     * @date 20:11 2021/6/22
     * @param param
     * @return org.elasticsearch.action.search.SearchRequest
     **/
    private SearchRequest bulidSearchRequest(SearchParam param) {
        //构建DSL语句
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //构建 bool
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //构建 must
        if(StringUtils.isNotBlank(param.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
        //1.2 bool filter
        //1.2.1 catalog
        if(null !=param.getCatalog3Id()){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }
        //1.2.2 brandId
        if(null != param.getBrandId() && param.getBrandId().size() > 0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }
        //1.2.3 hasStock
        if(null != param.getHasStock()){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",1== param.getHasStock()));
        }
        //范围函数  range
        //1.2.4 priceRange
        RangeQueryBuilder  rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
        if(StringUtils.isNotBlank(param.getSkuPrice())){
            String[] skuPrice = param.getSkuPrice().split("-");
            if(skuPrice.length==2){
                rangeQueryBuilder.gte(skuPrice[0]);
                rangeQueryBuilder.lte(skuPrice[1]);
            } else {
                if(param.getSkuPrice().startsWith("_")){
                    rangeQueryBuilder.gte(skuPrice[0]);
                } else {
                    rangeQueryBuilder.lte(skuPrice[0]);
                }
            }
            boolQueryBuilder.filter(rangeQueryBuilder);
        }
        //1.2.5 attrs-nested
        //attrs=1_5寸:8寸&2_16G:8G
        List<String> attrs = param.getAttrs();
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        if(null != attrs && attrs.size()>0){
            attrs.forEach(attr->{
                String[] attrSplit = attr.split("_");
                queryBuilder.must(QueryBuilders.termQuery("attrs.attrId",attrSplit[0]));
                String[] attrValues = attrSplit[1].split(":");
                queryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
            });
        }
        NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs",queryBuilder, ScoreMode.None);
        boolQueryBuilder.filter(nestedQueryBuilder);
        //1.X bool query构建完成
        searchSourceBuilder.query(boolQueryBuilder);
        //2. sort  eg:sort=saleCount_desc/asc
        if(StringUtils.isNotBlank(param.getSort())){
            String[] sortSplit = param.getSort().split("_");
            searchSourceBuilder.sort(sortSplit[0],sortSplit[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC);
        }
        //3. 分页 检测结果分页
        searchSourceBuilder.from((param.getPageNum()-1)*EsConstant.PRODUCT_PAGE_SIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGE_SIZE);
        //4. 高亮highlight
        if(StringUtils.isNotBlank(param.getKeyword())){
            HighlightBuilder highlightBuilder =  new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }
        //5. 聚合
        //5.1 按照brand聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg").field("brandId").size(10);
        TermsAggregationBuilder brandNameAgg = AggregationBuilders.terms("brandNameAgg").field("brandName");
        TermsAggregationBuilder brandImgAgg = AggregationBuilders.terms("brandImgAgg").field("brandImg");
        //子聚合
        brandAgg.subAggregation(brandImgAgg);
        brandAgg.subAggregation(brandNameAgg);
        searchSourceBuilder.aggregation(brandAgg);
        //5.2 按照catalog聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalogAgg").field("catalogId");
        TermsAggregationBuilder catalogNameAgg = AggregationBuilders.terms("catalogNameAgg").field("catalogName");
        catalogAgg.subAggregation(catalogNameAgg);
        searchSourceBuilder.aggregation(catalogAgg);
        //5.3 按照attrs聚合
        NestedAggregationBuilder nestedAggregationBuilder = new NestedAggregationBuilder("attrs","attrs");
        //按照attrId聚合     //按照attrId聚合之后再按照attrName和attrValue聚合
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId");
        TermsAggregationBuilder attrNameAgg = AggregationBuilders.terms("attrNameAgg").field("attrs.attrName");
        TermsAggregationBuilder attrValueAgg = AggregationBuilders.terms("attrValueAgg ").field("attrs.attrValue");
        attrIdAgg.subAggregation(attrNameAgg);
        attrIdAgg.subAggregation(attrValueAgg);
        nestedAggregationBuilder.subAggregation(attrIdAgg);
        searchSourceBuilder.aggregation(nestedAggregationBuilder);

        log.debug("构建的DSL语句 {}",searchSourceBuilder.toString());

        SearchRequest request = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
        return request;
    }

    /**
     * 响应参数封装处理
     * @author GuLin
     * @date 20:11 2021/6/22
     * @param param
     * @param response
     * @return com.example.gulimall.search.vo.SearchResult
     **/
    private SearchResult bulidSearchResult(SearchParam param, SearchResponse response) {
        SearchResult result = new SearchResult();
        SearchHits hits = response.getHits();
        //1. 封装查询到的商品信息
        if(null != hits.getHits() && hits.getHits().length>0){
            List<SkuEsModel> skuEsModels = new ArrayList<>();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                //设置高亮属性
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String highLight = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(highLight);
                }
                skuEsModels.add(skuEsModel);
            }
            result.setProducts(skuEsModels);
        }
        //2. 封装分页信息
        //2.1 当前页码
        result.setPageNum(param.getPageNum());
        //2.2总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //2.3 总页码
        Integer totalPage = (int)total%EsConstant.PRODUCT_PAGE_SIZE==0?
                (int)total/EsConstant.PRODUCT_PAGE_SIZE:(int)total/EsConstant.PRODUCT_PAGE_SIZE+1;
        result.setTotalPages(totalPage);
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPage; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        //3. 查询结果涉及到的品牌
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        Aggregations aggregation = response.getAggregations();
        //ParsedLongTerms用于接收terms聚合的结果，并且可以把key转化为Long类型的数据
        ParsedLongTerms brandAgg = aggregation.get("brandAgg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            //3.1 得到品牌id
            Long brandId = bucket.getKeyAsNumber().longValue();
            Aggregations subBrandAggs = bucket.getAggregations();
            //3.2 得到品牌图片
            ParsedStringTerms brandImgAgg = subBrandAggs.get("brandImgAgg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            //3.3 得到品牌名字
            Terms brandNameAgg = subBrandAggs.get("brandNameAgg");
            String brandName  = brandNameAgg.getBuckets().get(0).getKeyAsString();
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo(brandId, brandName, brandImg);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);
        //4. 查询涉及到的所有分类
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalogAgg = aggregation.get("catalogAgg");
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            Long catalogId  = bucket.getKeyAsNumber().longValue();
            Aggregations subcatalogAggs = bucket.getAggregations();
            ParsedStringTerms catalogNameAgg = subcatalogAggs.get("catalogNameAgg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo(catalogId, catalogName);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
        //5 查询涉及到的所有属性
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        //ParsedNested用于接收内置属性的聚合
        ParsedNested parsedNested = aggregation.get("attrs");
        ParsedLongTerms attrIdAgg=parsedNested.getAggregations().get("attrIdAgg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            //5.1 查询属性id
            Long attrId = bucket.getKeyAsNumber().longValue();
            Aggregations subAttrAgg = bucket.getAggregations();
            //5.2 查询属性名
            ParsedStringTerms attrNameAgg = subAttrAgg.get("attrNameAgg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            ParsedStringTerms attrValueAgg = subAttrAgg.get("attrValueAgg");
            List<String> attrValues = new ArrayList<>();
            if(null != attrValueAgg){
                for (Terms.Bucket attrValueAggBucket : attrValueAgg.getBuckets()) {
                    String attrValue = attrValueAggBucket.getKeyAsString();
                    attrValues.add(attrValue);
                }
            }
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo(attrId, attrName, attrValues);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);
        // 6. 构建面包屑导航
        List<String> attrs = param.getAttrs();
        if(null != attrs && attrs.size()>0){
            List<SearchResult.NavVo> navVos = attrs.stream().map(attr->{
                String[] attrSplit = attr.split("_");
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                //6.1设置属性
                navVo.setNavValue(attrSplit[1]);
                //6.2查询并设置属性名
                try {
                    R r = productFeignService.attrInfo(Long.valueOf(attrSplit[0]));
                    if(r.getCode() == 0){
                        AttrResponseVo attrResponseVo = r.getData("attr",new TypeReference<AttrResponseVo>(){});
                        navVo.setName(attrResponseVo.getAttrName());
                    } else {
                        navVo.setName(attrSplit[0]);
                    }
                } catch (Exception e) {
                    log.error("es分类查询获取属性信息失败 {}"+e.getMessage());
                    navVo.setName(attrSplit[0]);
                }
                //6.3 设置面包屑跳转链接
                String queryString = param.get_queryString();
                String replace = queryString.replace("&attrs=" + attr, "").replace("attrs=" + attr+"&", "").replace("attrs=" + attr, "");
                navVo.setLink("http://search.gulimall.com/search.html" + (replace.isEmpty()?"":"?"+replace));
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navVos);
        }
        return result;
    }


}
